const Koa = require("koa");
const mysql = require("mysql");
const serve = require("koa-static");
const bodyParser = require("koa-bodyparser");

const { matchTableNameAndFeids, showddl, parsejsonfromddl} = require("./service");
const { getDatabases, sqliteInit, saveDatabase } = require("./sqlite.js");
sqliteInit();

const app = new Koa();
// 使用中间件函数来解析请求体
app.use(bodyParser());

app.use(serve(__dirname + "/public"));

app.use(async (ctx) => {
  if (
    ctx.request.path === "/api/matchTableNameAndFeids" &&
    ctx.request.method === "GET"
  ) {
    const searchString = ctx.request.query.searchString;
    const databaseId = ctx.request.query.databaseId;

    var result = await matchTableNameAndFeids({
      searchString,
      databaseId,
    });
    ctx.body = {
      matchedTableNames: result.tableNames,
      matchedFields: result.fieldNames,
    };
  }
  if (
    ctx.request.path === "/api/getDatabases" &&
    ctx.request.method === "GET"
  ) {
    var list = await getDatabases();
    ctx.body = {
      data: list || [],
    };
  }

  if (ctx.request.path === "/api/showddl" && ctx.request.method === "GET") {
    const tableName = ctx.request.query.tableName;
    const databaseId = ctx.request.query.databaseId;
    var ddlstr = await showddl({
      tableName,
      databaseId,
    });
    ctx.body = {
      data: ddlstr,
    };
  }

  if (
    ctx.request.path === "/api/saveDatabase" &&
    ctx.request.method === "POST"
  ) {
    const body = ctx.request.body;
    saveDatabase(body);
    ctx.body = {};
  }
  if (
    ctx.request.path === "/api/updateDatabase" &&
    ctx.request.method === "POST"
  ) {
    const body = ctx.request.body;
    saveDatabase(body);
    ctx.body = {};
  }

  if (
      ctx.request.path === "/api/getjsonfromddl" &&
      ctx.request.method === "POST"
  ) {
    const ddl = ctx.request.body.ddl;
    var result = await parsejsonfromddl(ddl);
    ctx.body =result
  }


});

console.log("项目启动:8010");

app.listen(8010);
